package com.rmondjone.androidcamerademo

import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.rmondjone.camera.BitmapUtils
import com.rmondjone.camera.CameraActivity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

/**
 * copyright：
 * @author：anthui creation date： .
 * @since: 1.0.0
 * @describe:
 */
class MyCameraActivity : CameraActivity() {

    lateinit var typeAdapter: TypeAdapter

    var typeBean: TypeBean? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)


        if (MainActivity.data == null) {
            return
        }

        MainActivity.data?.firstOrNull()?.let {
            checkType(it)

        }

        findViewById<RecyclerView>(R.id.rv_type).apply {

            layoutManager = LinearLayoutManager(this@MyCameraActivity).apply {
                orientation = LinearLayoutManager.HORIZONTAL
            }

            typeAdapter = TypeAdapter()
            adapter = typeAdapter
            typeAdapter.setOnItemClickListener { adapter, view, position ->
                checkType(typeAdapter.data[position])
                typeAdapter.notifyDataSetChanged()

            }
        }


        typeAdapter.setNewData(MainActivity.data)


    }

    private fun checkType(typeBean: TypeBean) {
//        this.typeBean?.isCheck = false
//        typeBean.isCheck = true
//        this.typeBean = typeBean
//        Log.e("msg", "url----------- " + typeBean.image)
//        tvTitle.text = ""
//        tvtips.text = typeBean.description ?: ""
//        Glide.with(this).load(typeBean.image).into(mMaskImage)
    }

    override fun takePicture(data: ByteArray, isFont: Boolean) {

        GlobalScope.launch(Dispatchers.IO) {


            val options = BitmapFactory.Options()

            options.inSampleSize = 3

            val bitmap = BitmapFactory.decodeByteArray(data, 0, data.size, options)
            val cameraPath = Environment.getExternalStorageDirectory().path + File.separator + "DCIM" + File.separator + "Camera"
            //相册文件夹
            val cameraFolder = File(cameraPath)
            if (!cameraFolder.exists()) {
                cameraFolder.mkdirs()
            }
            //保存的图片文件
            val simpleDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss")
            val imagePath = cameraFolder.absolutePath + File.separator + "IMG_" + simpleDateFormat.format(Date()) + ".jpg"

            Log.e("msg", "m---------- width2-- " + bitmap.width + "  height-- " + bitmap.height)

            var changeBitMap = changeBitMap(bitmap, true)
            BitmapUtils.saveBitmap(changeBitMap, imagePath)

            withContext(Dispatchers.Main) {


                typeBean?.let {
                    var intent = Intent(this@MyCameraActivity, FaceActivity::class.java)
                    intent.putExtra("path", imagePath)
                    intent.putExtra("typeId", it.id)
                    startActivity(intent)
                }

            }

        }
    }

    fun savePhoto(imageData: ByteArray, isFont: Boolean): String {

        val cameraPath = Environment.getExternalStorageDirectory().path + File.separator + "DCIM" + File.separator + "Camera"
        //相册文件夹
        val cameraFolder = File(cameraPath)
        if (!cameraFolder.exists()) {
            cameraFolder.mkdirs()
        }
        //保存的图片文件
        val simpleDateFormat = SimpleDateFormat("yyyyMMdd_HHmmss")
        val imagePath = cameraFolder.absolutePath + File.separator + "IMG_" + simpleDateFormat.format(Date()) + ".jpg"
        val options = BitmapFactory.Options()
        options.inSampleSize = 5
        var bitmap = BitmapFactory.decodeByteArray(imageData, 0, imageData.size, options)
        Log.e("msg", "bitMap------- " + bitmap.width + "  height--   " + bitmap.height)

        val matrix = Matrix()
        if (isFont) {
            //旋转 180度
            matrix.postRotate(180f)
            //加入翻转 把相机拍照返回照片转正
            matrix.postScale(-1f, 1f)
        }
        bitmap = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.width, bitmap.height, matrix, true)
        Log.e("msg", "bitMap------2- " + bitmap.width + "  height--   " + bitmap.height)
        BitmapUtils.saveBitmap(bitmap, imagePath)
        bitmap.recycle()
        return imagePath
    }


    fun changeBitMap(bitmap: Bitmap, isFont: Boolean): Bitmap {

        val width = bitmap.width
        val widthRate = 750f / width
        val matrix = Matrix()
        if (isFont) {
            //旋转 180度
            matrix.postRotate(180f)
            //加入翻转 把相机拍照返回照片转正
            matrix.postScale(-1f * widthRate, 1f * widthRate)
        } else {
            matrix.postScale(widthRate, widthRate)
        }


        val bitmaps = Bitmap.createBitmap(bitmap, 0, 0,
                bitmap.width, bitmap.height, matrix, true)

        Log.e("msg", "m---------- width-- " + bitmaps.width + "  height-- " + bitmaps.height)
        return bitmaps

    }

    fun capBitMap(bitmap: Bitmap): Bitmap {

        val width = bitmap.width * 1f
        val height = bitmap.height * 1f
//        val matrix = Matrix()

        //当前的一个比例
        var currentRate = width / height

        //需要的一个比例
        var imageRate = getImageRate()

        if (currentRate == imageRate) {
            return bitmap
        }

        var x = 0f
        var y = 0f
        var realWidth = width
        var realHeght = height
        //当前比例大于要 显示的比例 说明 当前宽度比较大，裁剪万毒
        if (currentRate > imageRate) {

            x = (width - width * imageRate) / 2
            realWidth = width * imageRate
        } else {


            y = (height - height * imageRate) / 2
            realHeght = height * imageRate

        }


        val bitmaps = Bitmap.createBitmap(bitmap, x.toInt(), y.toInt(),
                realWidth.toInt(), realHeght.toInt())

        Log.e("msg", "m---------- width-- " + bitmaps.width + "  height-- " + bitmaps.height)
        return bitmaps

    }

    private fun getImageRate(): Float {
        val width: Float = (mPreviewLayout.width.toFloat()) / mPreviewLayout.height
        return width
    }
}